package F.树;

public class _617_合并二叉树 {
    /**
     * 自解：思路：规定从根节点开始 所以采用先序遍历 递归调用
     * 如果两个节点都是null 则返回null  只有一个为空 就返回该节点的值
     * @param t1
     * @param t2
     * --时间百分百 空间仅仅14
     * @return
     */
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {

        if(t1 == null && t2 == null){
            return null;
        }

        TreeNode node =null;
        if (t1==null){
            return t2;
        }else if (t2== null){

           return t1;

        }else {
            node = new TreeNode(t1.val+ t2.val);
//            t1 = t1.left;
//            t2 = t2.left;
        }
        node.left = mergeTrees(t1.left,t2.left);
        node.right = mergeTrees(t1.right,t2.right);

        return node;

    }

    /**
     * 自解：优化---不用新生成节点 直接加在1上
     *
     */
    public TreeNode mergeTrees1(TreeNode t1, TreeNode t2) {

        //Z.dailyExercise._0223.TreeNode head_node =t1 == null? t1:t2;
        if(t1 == null && t2 == null){
            return null;
        }

        if (t1==null){
            return  t2;
        }else if (t2== null){

            return t1;

        }else {
            t1.val = t1.val+ t2.val;

//            t1 = t1.left;
//            t2 = t2.left;
        }
        t1.left = mergeTrees(t1.left,t2.left);
        t1.right = mergeTrees(t1.right,t2.right);

        return t1;


    }


}
